#include "byte_builder.h"

#include "logger.h"

CByteBuilder::CByteBuilder(IStegIO* pStegIO) : 
	mStegIO(pStegIO),
	mBufferRead(0),
	mBufferWrite(0),
	mBitsUsedRead(8),
	mBitsUsedWrite(0)
{
}

CByteBuilder::~CByteBuilder() 
{
}

int CByteBuilder::getBit(bool& pReadBit) 
{
	if(mBitsUsedRead >= 8)
	{
		switch (mStegIO->read(mBufferRead)) {
			case NStegIO::READ_STATE_ERROR:
			case NStegIO::READ_STATE_NODATA:
				printl(LL_ERR, __FILE__, "Send EOF for error/no-data.");
			case NStegIO::READ_STATE_EOF:
				return 0;
			case NStegIO::READ_STATE_DATA:
				break;
		}

		mBitsUsedRead = 0;
	}

	unsigned char lMask = (0x80 >> mBitsUsedRead);
	if((mBufferRead & lMask)) {
		pReadBit = true;
	}
	else {
		pReadBit = false;
	}
	mBitsUsedRead++;

	return 1;
}

bool CByteBuilder::putBit(bool pWriteBit)
{
	mBufferWrite <<= 1;
	if(pWriteBit == true) {
		mBufferWrite |= 0x01;
	}
	mBitsUsedWrite++;

	//printl(0, __FILE__, "putBit(%s) %u/8", pWriteBit ? "true" : "false", mBitsUsedWrite);

	if(mBitsUsedWrite >= 8)
	{
		mStegIO->write(mBufferWrite);
		mBitsUsedWrite = 0;
		mBufferWrite = 0;
	}

	return true;
}

